package model.event;

import java.io.IOException;
import javax.microedition.lcdui.Image;
import model.structs.Point;
import view.DWGameCanvas;
import view.layers.Layer;
import view.layers.UserLayer;

/**
 * 
 *
 * @author rhaq
 * @version 1.00 2009-05-11 Initial submission.
 */
public class PoliceChase implements Event
{
	private static Image image;

	private static final String imageSrc = "/copCruiser_small.png";

	private UserLayer eventLayer;

	private Layer userLayer;

	/**
	 * @throws IOException 
	 * 
	 */
	public PoliceChase(UserLayer eventLayer, Layer userLayer) throws IOException
	{
		if (image == null)
			image = Image.createImage(imageSrc);

		this.eventLayer = eventLayer;
		this.userLayer = userLayer;
	}

	private void moveAppropriately(boolean tooCloseX, boolean tooCloseY, int uX, int uY, int eX, int eY)
	{
		if (!tooCloseX)
		{
			if ( (uX > eX) && !tooCloseX )
				eventLayer.moveRight();

			else if (uX < eX)
				eventLayer.moveLeft();
		}

		if (!tooCloseY)
		{
			if (uY < eY)
				eventLayer.moveUp();

			else if (uY > eY)
				eventLayer.moveDown();
		}
	}

	/* (non-Javadoc)
	 * @see model.event.Event#process()
	 */
	public void process() throws InterruptedException
	{
		while (true)
		{
			Point userCoordinates = userLayer.getCurrent();
			Point eventCoordinates = eventLayer.getCurrent();

			int uX = userCoordinates.getX();
			int uY = userCoordinates.getY();
			int eX = eventCoordinates.getX();
			int eY = eventCoordinates.getY();
			int differenceX = Math.abs(uX-eX);
			int differenceY = Math.abs(uY-eY);
			int policeSpeed = eventLayer.getTransportation().getSpeed();
			boolean tooCloseX = differenceX < policeSpeed;
			boolean tooCloseY = differenceY < policeSpeed;

			if (tooCloseX)
				eventLayer.setCurrentX(uX);

			if (tooCloseY)
				eventLayer.setCurrentY(uY);

			if (tooCloseX && tooCloseY)
				break;

			else
				moveAppropriately(tooCloseX, tooCloseY, uX, uY, eX, eY);

			Thread.sleep(DWGameCanvas.DELAY);
		}
	}
}